package com.tc.travel.submitter.executor;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tc.travel.submitter.pojo.VisaForImportReturnReportDto;
import com.tc.travel.submitter.service.ReturnReportBo;
import com.tc.travel.util.Consts;
import com.tc.travel.util.HtmlUtil;
import com.tc.travel.util.HttpClientUtil;
import com.tc.travel.util.PropertyUtil;
import com.tc.travel.util.SleepUtil;
import com.tc.travel.util.StringUtil;
import com.tc.travel.util.exception.ComRuntimeException;

@Component
public class ReturnReportImportExecutor extends BaseExecutor {
	private static Logger log = Logger.getLogger(ReturnReportImportExecutor.class);

	@Autowired
	private ReturnReportBo returnReportBo;

	public void execute() {
		VisaForImportReturnReportDto visaDto = returnReportBo.getVisaForImportReturnReport();
		if (visaDto != null) {
			String cookie = sessionBo.getCookie();
			log.info("cookie:" + cookie);

			int returnReportState = Consts.RETURN_REPORT_STATE_IMPORT_SUCC;
			String errorMsg = "";

			try {
				log.info("downloadExcelFile...");
				String filePath = downloadExcelFile(visaDto);

				log.info("step1.openSearchVisaPage...");
				openSearchVisaPage(cookie);

				log.info("step2.getVisaIdentityId-->dest_visa_id:" + visaDto.getDestVisaId() + "...");
				SleepUtil.sleepRandom(3, 6);
				String visaIdentityId = getVisaIdentityId(visaDto.getDestVisaId(), cookie);
				log.info("visaIdentityId:" + visaIdentityId);

				log.info("step3.openPersonListLoginPage...");
				SleepUtil.sleepRandom(1, 3);
				openPersonListLoginPage(visaIdentityId, cookie);

				log.info("step4.clickUploadButton...");
				SleepUtil.sleepRandom(1, 3);
				String uploadPageKey = clickUploadButton(visaIdentityId, cookie);
				log.info("uploadPageKey：" + uploadPageKey);

				log.info("step5.doUpload...");
				SleepUtil.sleepRandom(1, 3);
				doUpload(visaIdentityId, filePath, uploadPageKey, cookie);

			} catch (Throwable e) {
				returnReportState = Consts.RETURN_REPORT_STATE_IMPORT_FAIL;
				errorMsg = e.getMessage();
				log.error("import return report error. visa_info_id=" + visaDto.getVisaInfoId(), e);
			}

			log.info("updateReturnReportState:");
			returnReportBo.updateReturnReportState(visaDto.getVisaInfoId(), returnReportState, errorMsg);
		}
	}

	// step3. 点“个人名簿登录”按钮
	private void openPersonListLoginPage(String identityId, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameList;

		Map<String, String> params = new HashMap<String, String>();
		params.put("IDENTITY_ID", identityId);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_list.php");
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		HttpClientUtil.doGet(url, params, headers);
	}

	// step4.点“アップロード”(上传)按钮
	private String clickUploadButton(String identityId, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameUploadEdit;

		Map<String, String> params = new HashMap<String, String>();
		params.put("IDENTITY_ID", identityId);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_name_list.php?IDENTITY_ID=" + identityId);
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent",Consts.USER_AGENT);

		String html = HttpClientUtil.doGet(url, params, headers);
		assertUploadPage(html);

		String pageKey = HtmlUtil.getPageKey(html);
		if (StringUtil.isEmpty(pageKey)) {
			throw new ComRuntimeException("clickUploadButton error; no page key found.");
		}

		return pageKey;
	}

	private void assertUploadPage(String html) {
		if (StringUtil.isEmpty(html)) {
			throw new ComRuntimeException("clickUploadButton error; returned html is null.");
		}

		// if (html.indexOf("身元保証書発行内容") < 0 || html.indexOf("確認画面") < 0 || html.indexOf("査証種別") < 0) {
		// throw new ComRuntimeException("clickUploadButton error; html content error.");
		// }
	}

	// step5. 上传
	private void doUpload(String identityId, String filePath, String pageKey, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameUploadEdit;

		Map<String, String> params = new HashMap<String, String>();
		params.put("IDENTITY_ID", identityId);
		params.put("_PAGE_KEY", pageKey);
		params.put("BTN_SUBMIT_x", "登 録");

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding:gzip", "deflate, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Cache-Control", "max-age=0");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Origin", "https://churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_nameupload_edit.php?IDENTITY_ID=" + identityId);
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		HttpClientUtil.uploadFile(url, "CSV_FILE", filePath, params, headers);
	}

	// 从服务端下载归报excel文件
	private String downloadExcelFile(VisaForImportReturnReportDto visaDto) {
		String url = PropertyUtil.interfaceUrlDownload;

		Map<String, String> params = new HashMap<String, String>();
		params.put("fileType", Consts.FILE_TYPE_RETURN_REPORT_EXCEL);
		params.put("visaInfoId", visaDto.getVisaInfoId() + "");

		Map<String, String> headers = new HashMap<String, String>();

		String fileName = visaDto.getVisaInfoId() + ".xls";

		String filePath = HttpClientUtil.downloadFile(url, fileName, params, headers);
		return filePath;
	}

}
